<template>
  <div id="client">
    <div class="client-top" style="">
      <p style="margin-left: 20px">
        <span class="demonstration">单据日期：</span>
        <el-date-picker
          v-model="quotation.ddate"
          type="datetime"
          placeholder="选择日期时间"
          default-time="12:00:00"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
        &nbsp;&nbsp; 报价类型：
        <el-select
          placeholder="报价类型"
          style="width: 100px"
          v-model="quotation.dtype"
        >
          <el-option
            v-for="item in baojiatype"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option> </el-select
        >&nbsp;&nbsp; 客户主体：
        <el-select
          placeholder="客户主体"
          style="width: 100px"
          v-model="quotation.dentity"
          @change="handleSelectChange"
        >
          <el-option
            v-for="item in baojiabody"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option> </el-select
        >&nbsp;&nbsp; 销售员：
        <el-select
          placeholder="销售员"
          style="width: 100px"
          v-model="quotation.saleser"
        >
          <el-option
            v-for="item in salemen"
            :key="item.employeeId"
            :label="item.employeeName"
            :value="item.employeeCode"
          >
          </el-option>
        </el-select>
      </p>
      <p style="margin-top: 20px; margin-left: 20px">
        &nbsp;&nbsp;
        <span class="demonstration" style="margin-left: 20px">有效日期：</span>
        <el-date-picker
          type="daterange"
          v-model="effectiveDateRange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
        <span
          style="
            display: inline-block;
            float: right;
            position: relative;
            right: 100px;
          "
        >
          <el-button v-if="isOk" @click="rego()">新增</el-button>&nbsp;&nbsp;
          <el-button type="primary" @click="save()" v-if="isfind"
            >保存</el-button
          >&nbsp;&nbsp;
          <el-button type="primary" @click="verse()" v-if="isVese"
            >审核</el-button
          >&nbsp;&nbsp; <el-button v-if="isFvers">反审核</el-button>&nbsp;&nbsp;
          <el-button v-if="isFvers">生成销货订单</el-button>&nbsp;&nbsp;
          <el-button v-if="isFvers">生成销货单</el-button>&nbsp;&nbsp;

          <i
            class="el-icon-paperclip"
            style="color: blue; margin-left: 40px"
          ></i>
          <sapn style="color: blue">上传附件</sapn>
        </span>
      </p>
    </div>
    <div class="client-content" style="margin-top: 10px">
      <el-divider></el-divider>
      <div style="margin-top: 30px">
        <el-table
          height="300px"
          :data="tableData"
          border
          style="width: 100%; font-size: 13px"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" @click="removeRow(scope.$index)"
                >删除</el-button
              >
              <el-button size="mini" @click="addRow">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="gid" label="商品" width="230">
            <template slot-scope="scope">
              <el-input
                style="width: 120px; margin-left: 10px; margin-right: 20px"
                placeholder="请输入商品"
                v-model="scope.row.goodname"
                clearable
              ></el-input>
              <el-button
                style="margin-left: -20px; margin-right: 10px; width: 50px"
                @click="goodsShow = true"
                >...</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="goodname" label="商品名称" width="120">
          </el-table-column>
          <el-table-column prop="imagename" label="图片" width="120">
          </el-table-column>
          <el-table-column prop="unitid" label="基本单位" width="120">
          </el-table-column>
          <el-table-column prop="totalNum" label="基本数量" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.totalNum"
                placeholder="请输入基本数量"
                @input="calculateTotalPrice(scope.$index)"
                clearable
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="unitCost" label="单价" width="120">
          </el-table-column>
          <el-table-column prop="discount" label="折扣率" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.discount"
                placeholder="请输入折扣率"
                @input="calculateTotalPrice(scope.$index)"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="tax" label="税率" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.tax"
                placeholder="请输入税率"
                @input="calculateTotalPrice(scope.$index)"
                clearable
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="折后含税单价" width="120">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.totalPrice"
                placeholder="请输入折后含税单价"
                clearable
              ></el-input>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" @click="addRow">添加行</el-button>

        <el-input
          type="textarea"
          :rows="2"
          placeholder="暂无备注信息"
          style="width: 100%; line-height: 20px"
        >
        </el-input>
        <div style="float: right; margin-right: 20px; margin-top: 10px">
          <p>
            总金额（元）
            <el-input
              style="width: 200px; margin-left: 10px; margin-right: 20px"
              placeholder="请输入总金额"
              v-model="quotation.amount"
              disabled
              clearable
            >
            </el-input>
          </p>
          <p style="margin-top: 20px">
            <el-button type="primary" @click="goto('quoteList')"
              >历史单据</el-button
            >&nbsp;&nbsp; <el-button type="primary">操作日志</el-button>
          </p>
        </div>
      </div>

      <el-dialog top="20px" title="选择商品" :visible.sync="goodsShow">
        <GoodsChoose ref="chooseGoods" :goodsShow="goodsShow" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="goodsShow = false">取 消</el-button>
          <el-button type="primary" @click="yesGoods">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";
import ClientChoose from "../public_com/ClientChoose.vue";
import ClientLevelVue from "../information/ClientLevel.vue";
export default {
  name: "Quote",
  components: {
    GoodsChoose,
    ClientChoose,
  },
  data() {
    return {
      totaldiscount: 0,
      goodsShow: false,
      isOk: false,
      isLook: false,
      isVese: true,
      isFvers: false,
      baojiatype: [
        { value: "customer", label: "客户" },
        { value: "level", label: "客户等级" },
        { value: "type", label: "客户类型" },
      ],
      baojiabody: [],
      tableData: [
        {
          dNum: "",
          goodname: "",
          unitid: "",
          gid: "",
          totalNum: "",
          totalPrice: "",
          tax: "",
          discount: "",
          unitCost: "",
          goodname: "",
        },
      ],
      did: "",
      id: "",
      dNum: "",
      isfind: true,
      salemen: [],
      effectiveDateRange: [],
      quotation: {
        dnum: "",
        ddate: "",
        dentity: "",
        dtype: "",
        dstatus: 0,
        vstatus: 0,
        qstartTime: "",
        qendTime: "",
        saleser: "",
        dmethod: 5,
        quantity: 3,
        amount: 0,
        prepared: "727272",
        reviewer: "151215",
        preparationTime: "",
      },
    };
  },
  watch: {
    "quotation.dtype"(newVal) {
      this.updateBaojiabody(newVal);
    },
  },
  created() {
    var id = this.$route.params.id;
    var dNum = this.$route.params.dNum;
    if (typeof id === "undefined" || typeof dNum === "undefined") {
      this.id = "";
      this.dNum = "";
    } else {
      this.id = id;
      this.dNum = dNum;
      this.getQuote(this.id);
      this.getbydid(this.dNum);
    }
    this.updateBaojiabody(this.quotation.dtype);
    this.getSaler();
  },
  methods: {
    rego() {
      // 重置组件或进行其他操作
      this.$router.push({ name: "Quote" }); // 假设QuoteComponent是路由名称
    },
    handleSelectChange(newValue) {
      // 当选中值变化时，newValue即为选中的value
      const selectedItem = this.baojiabody.find(
        (item) => item.value === newValue
      );
      if (selectedItem) {
        // 获取选中项的discount值
        const discount = selectedItem.discount;
        // alert(discount)
        // 应用discount值，例如设置到quotation对象中

        this.tableData.forEach((item) => {
          item.discount = discount;
        });
        console.log(this.tableData);
      }
    },
    getbydid(dNum) {
      this.axios({
        url: "/sale/quoteDetail/one",
        params: {
          dNum: this.dNum,
        },
      }).then((rs) => {
        this.tableData = rs.data.quoteDetail;
        console.log(rs.data.quoteDetail);
      });
    },
    getQuote(id) {
      this.axios({
        url: "/sale/quote/getOne",
        params: {
          did: this.id,
        },
      }).then((rs) => {
        this.quotation = rs.data.quote;
        this.effectiveDateRange.push(this.quotation.qstartTime);
        this.effectiveDateRange.push(this.quotation.qendTime);

        console.log(rs.data.quote);
      });
    },
    getSaler() {
      this.axios({
        url: "/info/employee/listAll",
      }).then((rs) => {
        this.salemen = rs.data.list;
        console.log("saleMan", rs.data);
      });
    },
    updateBaojiabody(dtype) {
      if (dtype === "customer") {
        this.axios({
          url: "/info/client/allClient",
        }).then((rs) => {
          this.baojiabody = rs.data.clientList.map((client) => ({
            value: client.clientId,
            label: client.clientName,
          }));
        });
      } else if (dtype === "level") {
        this.axios({
          url: "/info/clientLevel/list",
        }).then((rs) => {
          console.log(rs.data.list);
          this.baojiabody = rs.data.list.map((ClientLevel) => ({
            value: ClientLevel.clientLevelId,
            label: ClientLevel.clientLevelName,
            discount: ClientLevel.discount,
          }));
          console.log(this.baojiabody);
        });
      } else if (dtype === "type") {
        this.axios({
          url: "/info/type/selectAll",
        }).then((rs) => {
          this.baojiabody = rs.data.typeList.map((type) => ({
            value: type.typeId,
            label: type.typeName,
          }));
        });
      }
    },
    calculateTotalPrice(index) {
      var price = 0;
      const row = this.tableData[index];
      row.totalPrice =
        row.totalNum *
        (1 - row.tax / 100) *
        (1 - row.discount / 100) *
        row.unitCost;
      this.tableData.forEach((item) => {
        price = price + item.totalPrice;
      });
      this.quotation.amount = price;
    },
    yesGoods() {
      this.goodsShow = false;
      // this.goodsList =
      // console.log(this.goodsList)
      //遍历商品列表
      this.inBoundList = this.$refs.chooseGoods.selectionList;
      console.log(this.inBoundList);
      const oid = this.id;
      this.inBoundList.forEach((item) => {
        this.tableData.push({
          dNum: "",
          gid: item.gid,
          goodname: item.goodname,
          unitname: item.unitname,
          unitId: item.unitId,
          stockId: item.stockId,
          totalNum: 0,
          totalPrice: 0,
          tax: 0,
          discount: 0,
          unitCost: item.unitCost,
        });
        var index1 = [];
        this.tableData.forEach((detail, index) => {
          if (detail.gid == "") {
            index1.push(index);
            console.log(index);
          }
        });
        index1.reverse().forEach((index, i) => {
          this.tableData.splice(index, 1);
        });
        console.log("tableData", this.tableData);
      });
    },
    addRow() {
      this.tableData.push({
        gid: "",
        unitname: "",
        goodname: "",
        goodcode: "",
        unitId: "",
        totalNum: "",
        totalPrice: "",
        tax: "",
        discount: "",
        unitCost: "",
      });
    },
    removeRow(index) {
      this.tableData.splice(index, 1);
    },
    goto(to) {
      this.$router.push(to);
    },

    save() {
      this.quotation.qstartTime = this.effectiveDateRange[0];
      this.quotation.qendTime = this.effectiveDateRange[1];

      if (this.dNum != "") {
        this.tableData.forEach((item) => {
          item.dNum = this.dNum;
          var quoteWrapper = new FormData();
          quoteWrapper = {
            quotation: JSON.stringify(this.quotation),
            tableData: JSON.stringify(this.tableData),
          };
          this.axios({
            url: "/sale/quote/update",
            method: "post",
            data: quoteWrapper,
          }).then((rs) => {
            alert(rs.data.status);
          });
        });
      } else {
        var quoteWrapper = new FormData();
        quoteWrapper = {
          quotation: JSON.stringify(this.quotation),
          tableData: JSON.stringify(this.tableData),
        };
        this.axios({
          url: "/sale/quote/add",
          method: "post",
          data: quoteWrapper,
        }).then((rs) => {
          if ((rs.data.status = true)) {
            this.did = rs.data.did;
            alert(this.did);
            alert("增加成功");
            this.isOk = true;
            this.isfind = false;
          } else {
            alert("增加失败");
          }
        });
      }
    },
    verse() {
      this.quotation.qstartTime = this.effectiveDateRange[0];
      this.quotation.qendTime = this.effectiveDateRange[1];
      console.log("quotation", this.quotation);
      console.log("tableData", this.tableData);
      var quoteWrapper = new FormData();

      quoteWrapper = {
        quotation: JSON.stringify(this.quotation),
        tableData: JSON.stringify(this.tableData),
      };

      if (this.isOk) {
        this.quotation.dnum = this.did;
        this.axios({
          url: "/sale/quote/updateStatus",
          data: {
            ...this.quotation,
          },
          method: "post",
        }).then((rs) => {
          console.log(rs.data.status);
          if (rs.data.status == true) {
            alert("审核成功");
            this.isVese = false;
            this.isFvers = true;
          } else {
            alert("审核失败");
          }
        });
      } else {
        this.axios({
          url: "/sale/quote/verse",
          method: "post",
          data: quoteWrapper,
        }).then((rs) => {
          if (rs.data.status == true) {
            alert("审核成功");
            this.isVese = false;
            this.isFvers = true;
          } else {
            alert("审核失败");
          }
        });
      }
    },
  },
};
</script>

<style scoped>
.el-button el-button--default el-popover__reference {
  margin-right: 20px;
}

tr {
  border: 1px solid black;
}
</style>